package com.earthchen.demo.util;

import com.earthchen.demo.vo.BaseTreeNodeVO;

import java.util.ArrayList;
import java.util.List;

/**
 * 树结构相关工具类
 *
 * @author earthchen
 * @date 2018/9/7
 **/
public class TreeUtil {

    /**
     * 用双重循环建树
     *
     * @param treeNodes treeNodes树节点列表
     * @param root      root根标志
     * @param <T>
     * @return
     */
    public static <T extends BaseTreeNodeVO> List<T> buildTreeBy2Loop(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<>();
        for (T node : treeNodes) {
            if (root == node.getParentId()) {
                trees.add(node);
            }

            for (T treeNode : treeNodes) {
                if (node.getId().equals(treeNode.getParentId())) {
                    if (node.getChildren() == null) {
                        node.setChildren(new ArrayList<>());
                    }
                    node.addChilren(treeNode);
                }
            }
        }
        return trees;
    }
}
